package org.sean.framework.canary.loadbalancer.predicate;

import org.sean.framework.canary.core.CanaryUtils;
import org.sean.framework.canary.loadbalancer.CanaryPredicate;
import org.sean.framework.util.StringUtil;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.http.HttpHeaders;

import java.util.Arrays;

/**
 * 选择默认版本
 *
 * @author xielei
 */
public class MainPredicate extends CanaryPredicate {
    private static String defaultLabel = "";

    /**
     * 设置全局默认Label
     *
     * @param label Label
     */
    public static void setDefaultLabel(String label) {
        if (StringUtil.isNotEmpty(label)) {
            defaultLabel = label;
        }
    }

    public static void reset() {
        defaultLabel = "";
    }

    @Override
    public boolean getSelector(ServiceInstance server, HttpHeaders headers) {
        String serverName = server.getServiceId();
        String serverLabel = CanaryUtils.getServerLabel(server);
        boolean result = Arrays.stream(defaultLabel.split(",")).anyMatch(item -> item.equalsIgnoreCase(serverLabel));
        logger.debug("[{}] : {} -label : [{}] -- rule label : [{}] -- match result : [{}]",
                serverName, server.getUri(), serverLabel, defaultLabel, result);
        return result;
    }
}
